import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/complaint.dart';
import '../services/database_service.dart';
import '../widgets/image_viewer.dart';
import '../widgets/video_player_widget.dart';

class ComplaintPage extends StatefulWidget {
  const ComplaintPage({super.key});

  @override
  State<ComplaintPage> createState() => _ComplaintPageState();
}

class _ComplaintPageState extends State<ComplaintPage> {
  final _formKey = GlobalKey<FormState>();
  final _phoneController = TextEditingController();
  final _descriptionController = TextEditingController();
  ComplaintType _selectedType = ComplaintType.air;
  String? _imagePath;
  String? _videoPath;
  String _address = '正在获取位置...';
  double? _latitude;
  double? _longitude;
  final LocationFlutterPlugin _locationPlugin = LocationFlutterPlugin();
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _initLocation();
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _descriptionController.dispose();
    _locationPlugin.stopLocation(); // 停止定位服务
    super.dispose();
  }

  Future<void> _initLocation() async {
    final status = await Permission.location.request();
    if (status.isGranted) {
      //设置隐私协议
      _locationPlugin.setAgreePrivacy(true);
      // 配置定位参数
      await _setupLocationOptions();
      // 监听定位结果
      _locationPlugin.seriesLocationCallback(
        callback: (BaiduLocation result) {
          if (result.latitude != null) {
            setState(() {
              _latitude = result.latitude;
              _longitude = result.longitude;
              _address = result.address ?? '未知位置';
            });
          } else {
            setState(() => _address = '定位失败：${result.errorInfo ?? '未知错误'}');
          }
        },
      );
    } else {
      setState(() => _address = '定位权限被拒绝');
    }
    // 启动定位
    _locationPlugin.startLocation();
  }

  Future<void> _setupLocationOptions() async {
    // Android配置
    BaiduLocationAndroidOption androidOptions = BaiduLocationAndroidOption(
      locationMode: BMFLocationMode.hightAccuracy,
      isNeedAddress: true,
      isNeedLocationPoiList: true,
      isNeedLocationDescribe: true,
      openGps: true,
      coordType: BMFLocationCoordType.bd09ll,
      scanspan: 2000,
    );

    // iOS配置
    BaiduLocationIOSOption iosOptions = BaiduLocationIOSOption(
      coordType: BMFLocationCoordType.bd09ll,
      desiredAccuracy: BMFDesiredAccuracy.best,
      allowsBackgroundLocationUpdates: true,
    );

    // 应用配置
    await _locationPlugin.prepareLoc(
      androidOptions.getMap(),
      iosOptions.getMap(),
    );
  }

  Future<void> _pickImage() async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.camera);
    if (image != null) {
      setState(() {
        _imagePath = image.path;
        _videoPath = null;
      });
    }
  }

  Future<void> _pickVideo() async {
    final ImagePicker picker = ImagePicker();
    final XFile? video = await picker.pickVideo(source: ImageSource.camera);
    if (video != null) {
      setState(() {
        _videoPath = video.path;
        _imagePath = null;
      });
    }
  }

  Future<void> _submitComplaint() async {
    if (!_formKey.currentState!.validate()) return;
    if (_latitude == null || _longitude == null) {
      Get.snackbar('错误', '请等待位置信息获取完成');
      return;
    }

    setState(() => _isLoading = true);

    try {
      final complaint = Complaint(
        phone: _phoneController.text,
        type: _selectedType,
        description: _descriptionController.text,
        imagePath: _imagePath,
        videoPath: _videoPath,
        latitude: _latitude!,
        longitude: _longitude!,
        address: _address,
        createdAt: DateTime.now(),
      );

      final db = DatabaseService();
      await db.insertComplaint(complaint);

      final controller = Get.find<ComplaintController>();
      controller.loadComplaints();

      // 自动拨打环保部门电话
      final Uri phoneUri = Uri(scheme: 'tel', path: '17712958202');
      if (await canLaunchUrl(phoneUri)) {
        await launchUrl(phoneUri);
      }

      Get.back();
      Get.snackbar('成功', '投诉已提交');
    } catch (e) {
      Get.snackbar('错误', '提交失败：$e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  void _showImage(BuildContext context) {
    if (_imagePath != null) {
      Get.to(() => ImageViewer(imagePath: _imagePath!));
    }
  }

  void _playVideo(BuildContext context) {
    if (_videoPath != null) {
      Get.to(() => VideoPlayerWidget(videoPath: _videoPath!));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('提交投诉')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              DropdownButtonFormField<ComplaintType>(
                value: _selectedType,
                decoration: const InputDecoration(
                  labelText: '投诉类型',
                  border: OutlineInputBorder(),
                ),
                items:
                    ComplaintType.values.map((type) {
                      String text;
                      switch (type) {
                        case ComplaintType.air:
                          text = '大气污染';
                          break;
                        case ComplaintType.water:
                          text = '水污染';
                          break;
                        case ComplaintType.soil:
                          text = '土壤污染';
                          break;
                      }
                      return DropdownMenuItem(value: type, child: Text(text));
                    }).toList(),
                onChanged: (value) {
                  if (value != null) {
                    setState(() => _selectedType = value);
                  }
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(
                  labelText: '联系电话',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.phone,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入联系电话';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _descriptionController,
                decoration: const InputDecoration(
                  labelText: '问题描述',
                  border: OutlineInputBorder(),
                ),
                maxLines: 3,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入问题描述';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  Expanded(
                    child: OutlinedButton.icon(
                      onPressed: _pickImage,
                      icon: const Icon(Icons.photo_camera),
                      label: const Text('拍照'),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: OutlinedButton.icon(
                      onPressed: _pickVideo,
                      icon: const Icon(Icons.videocam),
                      label: const Text('录像'),
                    ),
                  ),
                ],
              ),
              if (_imagePath != null || _videoPath != null) ...[
                const SizedBox(height: 16),
                Container(
                  height: 200,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child:
                      _imagePath != null
                          ? GestureDetector(
                            onTap: () => _showImage(context),
                            child: Stack(
                              fit: StackFit.expand,
                              children: [
                                Image.file(
                                  File(_imagePath!),
                                  fit: BoxFit.cover,
                                ),
                                Positioned(
                                  right: 8,
                                  top: 8,
                                  child: IconButton(
                                    icon: const Icon(
                                      Icons.close,
                                      color: Colors.white,
                                    ),
                                    onPressed: () {
                                      setState(() {
                                        _imagePath = null;
                                      });
                                    },
                                  ),
                                ),
                              ],
                            ),
                          )
                          : GestureDetector(
                            onTap: () => _playVideo(context),
                            child: Stack(
                              fit: StackFit.expand,
                              children: [
                                Container(
                                  color: Colors.black,
                                  child: const Center(
                                    child: Icon(
                                      Icons.play_circle_filled,
                                      color: Colors.white,
                                      size: 48,
                                    ),
                                  ),
                                ),
                                Positioned(
                                  right: 8,
                                  top: 8,
                                  child: IconButton(
                                    icon: const Icon(
                                      Icons.close,
                                      color: Colors.white,
                                    ),
                                    onPressed: () {
                                      setState(() {
                                        _videoPath = null;
                                      });
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                ),
              ],
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(16),
                width: double.infinity,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('当前位置：'),
                    const SizedBox(height: 8),
                    Text(_address),
                    const SizedBox(height: 8),
                    Text('纬度：${_latitude ?? 0} 经度：${_longitude ?? 0}'),
                  ],
                ),
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _isLoading ? null : _submitComplaint,
                child:
                    _isLoading
                        ? const CircularProgressIndicator()
                        : const Text('提交投诉'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
